from flask import jsonify, request, session

from models import db
from models.index import Comment, CommentLike
from views import news_blu


@news_blu.route("/news/comment", methods=["POST"])
def news_comment():
    # 1. 提取出用户评价时的数据
    content = request.json.get("content")
    news_id = request.json.get("news_id")
    user_id = session.get("user_id")
    if not user_id:
        ret = {
            "errno": "1001",
            "errmsg": "请先登录"
        }

        return jsonify(ret)

    parent_id = request.json.get("parent_id")

    # 2. 保存到数据库
    new_comment = Comment()
    new_comment.news_id = news_id
    new_comment.user_id = user_id
    new_comment.content = content
    new_comment.parent_id = parent_id
    db.session.add(new_comment)
    db.session.commit()

    ret = {
        "errno": 0,
        "errmsg": "成功"
    }
    return jsonify(ret)


@news_blu.route("/news/like_comment", methods=["POST"])
def news_like_comment():
    # 获取数据
    user_id = session.get("user_id")
    if not user_id:
        ret = {
            "errno": '1002',
            "errmsg": "请先登录"
        }

        return jsonify(ret)
    comment_id = request.json.get("comment_id")
    avtion = request.json.get("avtion")


    if avtion == "do":
        lm = CommentLike(comment_id=comment_id,user_id=user_id)
        db.session.add(lm)
        db.session.commit()
        ret = {
            "errno":'0',
            "errmsg":'请求成功'
        }

        return jsonify(ret)


    elif avtion == "undo":
        lm = db.session.query(CommentLike).filter(CommentLike.comment_id==comment_id,CommentLike.user_id==user_id).first()

        db.session.delete(lm)
        db.session.commit()
        ret = {
            "errno":"0",
            "errmsg":"请成功"
        }
        return jsonify(ret)
    else:
        ret = {
            "errno": "1000",
            "errmsg": "????"
        }
        return jsonify(ret)
